﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

using System.Runtime.InteropServices;

namespace mesRUpload
{
    public static class INIConfigAPI
    {
        const int SIZE = 1024 * 10; // 读取字符串最大长度

        public enum file_id
        {
            directory = 0x0000001
        }

        public enum webservice_id
        {
            MESWSDL = 0x0000001,
            TimeOut,
            User,
            Password
        }

        public enum request_id
        {
            site = 0x0000001,
            user,
            operation,
            operationRevision,
            resource,
            activityId,
            modeProcessSfc,
            dcGroup,
            dcGroupRevision,
            parametricDataArray,
            ncCodeArray
        }

        public static string commPath { set; get; }

        [DllImport("kernel32")] // 写入配置文件的接口
        private static extern long WritePrivateProfileString(
            string section, string key, string val, string filePath);

        [DllImport("kernel32")] // 读取配置文件的接口
        private static extern int GetPrivateProfileString(
            string section, string key, string def
            , StringBuilder retVal, int size, string filePath);

        // 配置文件路径初始化
        public static bool InitPath(string filepath)
        {
            commPath = filepath;

            Timing.start();

            try
            {
                if (!File.Exists(commPath))
                {
                    FileStream fs = new FileStream(commPath, FileMode.OpenOrCreate);
                    //WriteValue("CCFile", null, null);
                    WriteValue("webservice", null, null);
                    WriteValue("request", null, null);
                    WriteValue("parameters", null, null);
                    fs.Close();
                    return false;
                }

                return true;
            }
            catch (Exception e)
            {
                string filemessage = commPath + "," + "ini 文件," + Timing.startTime()
                       + "," + Timing.end() + "," + Timing.spendTime() + "," + "写入失败,"
                       + Timing.exceptionMess(e);
                MESUpload.errorLogger.Error(filemessage);

                MESUpload.logger.Warn("ini 文件写入失败");

                return false;
            }

        }

        // 向配置文件写入值
        private static void WriteValue(
            string section, string key, string value)
        {
            Timing.start();

            try
            {
                WritePrivateProfileString(section, key, value, commPath);
            }
            catch (Exception e)
            {
                string filemessage = commPath + "," + "ini 文件," + Timing.startTime()
                       + "," + Timing.end() + "," + Timing.spendTime() + "," + "写入失败,"
                       + Timing.exceptionMess(e);
                MESUpload.errorLogger.Error(filemessage);

                MESUpload.logger.Warn("ini 文件保存失败");
            }
        }

        /// 写入上次访问文件路径
        public static void WriteFile(string directory)
        {
            WriteValue("lastfile", "directory", directory);
        }

        // 写入 webservice 对应键值
        public static bool WriteWebservice(string MESWSDL, string TimeOut, string User
            , string Password)
        {
            try
            {
                WriteValue("webservice", "MESWSDL", MESWSDL);
                WriteValue("webservice", "TimeOut", TimeOut);
                WriteValue("webservice", "User", User);
                WriteValue("webservice", "Password", Password);

                return true;
            }
            catch (Exception e)
            {
                MESUpload.logger.Warn("ini 文件保存失败");

                string filemessage = commPath + "," + "ini 文件," + Timing.startTime()
                       + "," + Timing.end() + "," + Timing.spendTime() + "," + "写入失败,"
                       + Timing.exceptionMess(e);
                MESUpload.errorLogger.Error(filemessage);

                return false;
            }
        }

        // 写入 request 对应键值
        public static bool WriteRequest(bool isMachineRequest, string site, string user
            , string operation, string operationRevision, string activityId
            , string resource, string modeProcessSfc, string dcGroup = ""
            , string dcGroupRevision = "")
        {
            try
            {
                WriteValue("request", "site", site);
                WriteValue("request", "user", user);
                WriteValue("request", "operation", operation);
                WriteValue("request", "operationRevision", operationRevision);
                WriteValue("request", "resource", resource);
                WriteValue("request", "activityId", activityId);
                WriteValue("request", "modeProcessSfc", modeProcessSfc);
                if (isMachineRequest)
                {
                    WriteValue("request", "dcGroup", dcGroup);
                    WriteValue("request", "dcGroupRevision", dcGroupRevision);
                }

                return true;
            }
            catch (Exception e)
            {
                MESUpload.logger.Warn("ini 文件保存失败");

                string filemessage = commPath + "," + "ini 文件," + Timing.startTime()
                       + "," + Timing.end() + "," + Timing.spendTime() + "," + "写入失败,"
                       + Timing.exceptionMess(e);
                MESUpload.errorLogger.Error(filemessage);

                return false;
            }
        }
        public static void WriteRequest(string parametricDataArray, string ncCodeArray)
        {
            WriteValue("request", "parametricDataArray", parametricDataArray);
            WriteValue("request", "ncCodeArray", ncCodeArray);
        }

        // 读取配置文件的值
        private static string ReadValue(string section, string key)
        {
            Timing.start();

            try
            {
                StringBuilder strb = new StringBuilder(SIZE);
                GetPrivateProfileString(section, key, "", strb, SIZE, commPath);
                return strb.ToString().Trim();
            }
            catch (Exception e)
            {
                string filemessage = commPath + "," + "ini 文件," + Timing.startTime()
                       + "," + Timing.end() + "," + Timing.spendTime() + "," + "写入失败,"
                       + Timing.exceptionMess(e);
                MESUpload.errorLogger.Error(filemessage);

                MESUpload.logger.Warn("ini 文件读取失败");

                return "null";
            }
        }

        /// 读取上次文件访问路径
        public static string ReadFile(file_id id)
        {
            if (id == file_id.directory)
                return ReadValue("lastfile", "directory");
            else
                return "null";
        }

        /// 读取 webservice 对应键值
        public static string ReadWebservice(webservice_id id)
        {
            if (id == webservice_id.MESWSDL)
                return ReadValue("webservice", "MESWSDL");
            else if (id == webservice_id.TimeOut)
                return ReadValue("webservice", "TimeOut");
            else if (id == webservice_id.User)
                return ReadValue("webservice", "User");
            else if (id == webservice_id.Password)
                return ReadValue("webservice", "Password");
            else
                return "null";
        }

        // 读取 request 对应键值
        public static string ReadRequest(request_id id)
        {
            if (id == request_id.site)
                return ReadValue("request", "site");
            else if (id == request_id.user)
                return ReadValue("request", "user");
            else if (id == request_id.operation)
                return ReadValue("request", "operation");
            else if (id == request_id.operationRevision)
                return ReadValue("request", "operationRevision");
            else if (id == request_id.resource)
                return ReadValue("request", "resource");
            else if (id == request_id.activityId)
                return ReadValue("request", "activityId");
            else if (id == request_id.modeProcessSfc)
                return ReadValue("request", "modeProcessSfc");
            else if (id == request_id.dcGroup)
                return ReadValue("request", "dcGroup");
            else if (id == request_id.dcGroupRevision)
                return ReadValue("request", "dcGroupRevision");
            else if (id == request_id.parametricDataArray)
                return ReadValue("request", "parametricDataArray");
            else if (id == request_id.ncCodeArray)
                return ReadValue("request", "ncCodeArray");
            else
                return "null";
        }

        public static StringBuilder ReadArray()
        {
            StringBuilder sb = new StringBuilder();
            return sb.Append(ReadValue("request", "parametricDataArray"));
        }
    }
}
